package pers.xiqingbo.web;

import pers.xiqingbo.pojo.Cart;
import pers.xiqingbo.pojo.User;
import pers.xiqingbo.service.OrderService;
import pers.xiqingbo.service.impl.OrderServiceImpl;
import pers.xiqingbo.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @PackageName: ${PACKAGE_NAME}
 * @ClassName: ${NAME}
 * @Description: 订单管理业务表示层
 * @Author: Schieber
 * @Date: 2021/3/3 下午 20:24
 */
public class OrderServlet extends BaseServlet {

    private OrderService orderService = new OrderServiceImpl();

    /**
     * 生成订单方法
     *
     * @param request  请求
     * @param response 响应
     * @throws ServletException
     * @throws IOException
     */
    protected void createOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从Session中获取购物车对象
        Cart cart = (Cart) request.getSession().getAttribute("cart");

        // 从Session中获取user对象
        User user = (User) request.getSession().getAttribute("user");

        // 如果用户结算时未登录则跳转至登录页面
        if (user == null) {
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
            return;
        }

        // 获取userId
        int userId = user.getId();

        // 调用Service处理生成订单业务
        String orderId = null;
        orderId = orderService.createOrder(cart, userId);

        // 将订单号共享至Session域中
        request.getSession().setAttribute("orderId", orderId);

        // 重定向至结算页面
        response.sendRedirect("pages/cart/checkout.jsp");
    }
}
